//
//  SignInView.m
//  NewPro
//
//  Created by RYX on 2019/1/15.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "SignInView.h"

@implementation SignInView {
    BOOL _isTurning;  // 是否正在翻转
    BOOL _isReversed; // 是否反面朝上
}

- (instancetype)init {
    if (self = [super init]) {
        _isTurning  = NO;
        _isReversed = NO;
        [self setUI];
    }
    return self;
}

- (void)setUI{
    
    UIButton *topBtn = [[UIButton alloc] init];
    [topBtn setImage:[UIImage imageNamed:@"签到"] forState:UIControlStateNormal];
    [self addSubview:topBtn];
    [self bringSubviewToFront:topBtn];
    _topBtn = topBtn;
    
    UIButton *bottomBtn = [[UIButton alloc] init];
    [bottomBtn setImage:[UIImage imageNamed:@"已签到"] forState:UIControlStateNormal];
    [self addSubview:bottomBtn];
    [self sendSubviewToBack:bottomBtn];
    _bottomBtn = bottomBtn;
    
    [topBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    
        make.edges.equalTo(self);
        
    }];
    
    [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {

        make.edges.equalTo(self);

    }];
    
}

/**
 翻转
 
 @param duration 翻转动画所需时间
 @param completion 动画结束后的回调
 */
- (void)turnWithDuration:(NSTimeInterval)duration completion:(void(^)(void))completion{
    if (!self.topBtn || !self.bottomBtn) {
        NSAssert(NO, @"未设置topBtn或bottomBtn");
    }
    
    // 正在动画中不能重复执行
    if (_isTurning) {
        return;
    }
    
    _isTurning = YES;
    
    if (_isReversed) { // 此时反面朝上
        // 从反面翻转到正面
        [UIView transitionFromView:self.bottomBtn toView:self.topBtn duration:duration options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished) {
            !completion ?: completion();
            _isTurning  = NO;
            _isReversed = NO;
        }];
    } else { // 此时正面朝上
        // 从正面翻转到反面
        [UIView transitionFromView:self.topBtn toView:self.bottomBtn duration:duration options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished) {
            !completion ?: completion();
            _isTurning  = NO;
            _isReversed = YES;
        }];
    }
}

@end
